import React, { Component } from 'react'
let {Provider, Consumer} = React.createContext()

class CartButton extends Component {
  render() {
    return (
      <Consumer>
        {
          ({handleCount})=>{
            let { type } = this.props
            return (
              <button
              onClick={
                ()=>{
                  // type === 'add' ? handleAdd() : handleSub()
                  handleCount(type)
                }
              }>
                {type === 'add' ? '+' : '-'}
              </button>
            )
          }
        }
      </Consumer>
    )
  }
}

class Counter extends Component {
  render() {
    return (
      <Consumer>
        {
          ({num}) => {
            return <span>{num}</span>
          }
        }
      </Consumer>
    )
  }
}

class Test extends Component {
  render() {
    return <div>{this.props.children}</div>
  }
}

export default class App extends Component {
  state = {
    num: 666
  }
  // handleAdd = ()=> {
  //   this.setState(state=>{
  //     return {
  //       num: ++state.num
  //     }
  //   })
  // }
  // handleSub = ()=> {
  //   this.setState(state=>({
  //     num: --state.num
  //   }))
  // }
  handleCount = (type) => {
    type === 'add' ? this.setState(state=>(
      {
        num: ++state.num
      }
    )) : this.setState(state=>({
      num: --state.num
    }))
  }
  render() {
    return (
      <div>
        <Provider
        value={
          {
            num: this.state.num,
            handleCount: this.handleCount
          }
        }>
          <Test>
            <CartButton type='add'></CartButton>
            <Counter></Counter>
            <CartButton type='sub'></CartButton>
          </Test>
        </Provider>
      </div>
    )
  }
}
